package LinkedList;

import Utils.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 反转链表
 * Lettcode 206: https://leetcode-cn.com/problems/reverse-linked-list/
 */
public class reverseList {
    /**
     * 方法一：利用一个数组存储链表,效率低，空间大
     * @param head
     * @return reversed list
     */
    public ListNode reverseList(ListNode head) {
        List<Integer> temp = new ArrayList<>();
        ListNode res = new ListNode(0);
        while (head != null) {
            temp.add(head.val);
            head = head.next;
        }
        ListNode movePoint = res;
        for (int i = temp.size() - 1; i >= 0; i--) {
            ListNode newNode = new ListNode(temp.get(i));
            movePoint.next = newNode;
            movePoint = movePoint.next;
        }
        return res.next;
    }

    /**
     * 方法二： 改变指针指向
     * @param head
     * @return reversed list
     */
    public ListNode reverseListI(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    public ListNode reverseListII(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
}
